//
//  ListViewVC.m
//  UILbrary
//
//  Created by Apple on 2022/5/8.
//  Copyright © 2022 mac. All rights reserved.
//

#import "ListViewVC.h"
#import "MYHeader.h"
#import "ListViewVC.h"

@interface ListViewVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSArray *datas;
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ListViewVC

+ (NSArray *)arrFromJsonName:(NSString *)json
{
    NSString *path = [[NSBundle mainBundle] pathForResource:json ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    NSArray *arr = dic[@"data"];
    return arr;
}

+ (UIViewController *)pushViewController:(NSDictionary *)dic
{
    NSString *classString = dic[ListViewVC_DATA_VC_KEY];
    UIViewController *vc = [UIViewController new];
    if ([classString isEqual:NSStringFromClass([ListViewVC class])]) {
        NSString *jsonName = dic[ListViewVC_DATA_jsonFileName_KEY];
        vc = [[ListViewVC alloc] initWithDatas:[ListViewVC arrFromJsonName:jsonName]];
    }else{
        vc = [NSClassFromString(classString) new];
    }
    return vc;
}

//MARK: - system

- (instancetype)initWithDatas:(NSArray *)datas;
{
    if(self = [super init]){
        _datas = datas;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0    ));
    }];
}

//MARK: - UITableViewDelegate UITableViewDataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    NSString *title = [NSString stringWithFormat:@"%ld_%@",indexPath.row + 1, self.datas[indexPath.row][ListViewVC_DATA_TITLE_KEY]];
    cell.textLabel.text = title;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *classString = self.datas[indexPath.row][@"ListViewVC_DATA_VC_KEY"];
    UIViewController *vc = [NSClassFromString(classString) new];
    [self.navigationController pushViewController:vc animated:YES];
}


//MARK: - get

- (UITableView *)tableView
{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

//MARK: - test

- (void)test
{
    [self test_1];
}

- (void)test_1
{

}

@end
